from PySide2.QtCore import QThread, Signal, Qt
from PySide2.QtGui import QImage, QPixmap
from pathlib import Path

import cv2
import json

from tool import util, dbutil
import kuaikandian
from manager import Manager

import time
import subprocess

class LoadImage(QThread):

    finishsignal = Signal(str, QPixmap)

    def __init__(self):
        super(LoadImage, self).__init__()

    def setImg(self, id, img):
        self.id = id;
        self.img = img

    def run(self):
        self.cap = cv2.VideoCapture(self.img)
        success, frame = self.cap.read()
        if not success:
            return
        show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        showImage = QImage(show.data, show.shape[1], show.shape[0], show.shape[1]*3, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(showImage)
        self.finishsignal.emit(str(self.id), pixmap)

    def stop(self):
        self.quit()


class OnPlay(QThread):
    
    finishsignal = Signal(list)

    def __init__(self, id, url):
        super(OnPlay, self).__init__()
        self.url = url
        self.id = id

    def run(self):
        if self.url.find(".mp4") != -1:
            urls = self.url.split(',')
            self.finishsignal.emit(urls)
            return

        if self.url.find("http") != -1:
            # 远程
            command = "you-get --json " + self.url
            str = util.terminal(command)
            data = json.loads(str)
            urls = data['streams']['__default__']['src']
            real_url = ",".join(urls)

            dbutil.updateVideo(self.id, {"real_url": real_url})
            # 真实地址
            self.finishsignal.emit(urls)

        # command = "ffplay " + self.url
        # util.terminal(command)

        # self.finishsignal.emit()

class OnPlayFFmpeg(QThread):
    finishsignal = Signal()

    def __init__(self, url):
        super(OnPlayFFmpeg, self).__init__()
        self.url = url

    def run(self):
        command = "ffplay " + self.url
        util.terminal(command)
        self.finishsignal.emit()

class OnDownload(QThread):
    finishsignal = Signal()

    def __init__(self, url, name=None, dir='videos'):
        super(OnDownload, self).__init__()
        Path(dir).mkdir(parents=True, exist_ok=True)
        self.url = url
        self.dir = dir
        self.name = name

    def run(self):
        command = "you-get " + self.url
        if self.dir != None:
            command = command + " -o " + self.dir
        if self.name != None:
            command = command + " -O " + self.name
        util.terminal(command)
        outfile = str(Path(self.dir+"/"+self.name+".mp4"))

        self.finishsignal.emit(outfile)


class OnDownloadAndOther(QThread):
    finishsignal = Signal(str)

    def __init__(self, url, name=None, dir='videos'):
        super(OnDownloadAndOther, self).__init__()
        Path(dir).mkdir(parents=True, exist_ok=True)
        self.url = url
        self.dir = dir
        self.name = name

    def run(self):
        download_name = self.name + "_download"
        command = "you-get " + self.url
        if self.dir != None:
            command = command + " -o " + self.dir
        if self.name != None:
            command = command + " -O " + download_name
        util.terminal(command)

        # 裁剪第一秒
        infile = str(Path(self.dir+"/"+download_name+".mp4"))
        outfile = str(Path(self.dir+"/"+self.name+".mp4"))
        command = 'ffmpeg -ss 1 -i ' + infile + ' -acodec copy -vcodec copy ' + outfile + ' -y'
        util.terminal(command)
        Path(infile).unlink()

        self.finishsignal.emit(outfile)

class OnUploadVideo(QThread):
    upload_finish_signal = Signal()

    def __init__(self, videos):
        super(OnUploadVideo, self).__init__()
        self.videos = videos

    def run(self):
        kuaikandian.open(
            Manager.currentUploador.account, Manager.currentUploador.pwd, self.videos)
        self.upload_finish_signal.emit()
